package com.ebocy.hammer.core.message;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;

public abstract class AbstractC2SMessage implements IMessage {
	private static final CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
	private IoBuffer ioBuffer;

	public AbstractC2SMessage() {
	}

	public void setIoBuffer(IoBuffer ioBuffer) {
		this.ioBuffer = ioBuffer;
	}

	public abstract short getMessageCode();

	public abstract void readMessage();

	protected long readLong() {
		return this.ioBuffer.getLong();
	}

	protected byte readByte() {
		return this.ioBuffer.get();
	}

	protected short readShort() {
		return this.ioBuffer.getShort();
	}

	protected int readInt() {
		return this.ioBuffer.getInt();
	}

	protected float readFloat() {
		return this.ioBuffer.getFloat();
	}

	protected String readString() {
		try {
			short length = this.ioBuffer.getShort();
			return this.ioBuffer.getString(length, utf8Decoder);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected byte[] readByteArray() {
		short size = ioBuffer.getShort();
		byte[] result = new byte[size];
		for (int i = 0; i < size; i++)
			result[i] = ioBuffer.get();
		return result;
	}

	protected short[] readShortArray() {
		short size = ioBuffer.getShort();
		short[] result = new short[size];
		for (int i = 0; i < size; i++)
			result[i] = ioBuffer.getShort();
		return result;
	}

	protected int[] readIntArray() {
		short size = ioBuffer.getShort();
		int[] result = new int[size];
		for (int i = 0; i < size; i++)
			result[i] = ioBuffer.getInt();
		return result;
	}

	protected float[] readFloatArray() {
		short size = ioBuffer.getShort();
		float[] result = new float[size];
		for (int i = 0; i < size; i++)
			result[i] = ioBuffer.getFloat();
		return result;
	}

	protected String[] readStringArray() {
		short size = ioBuffer.getShort();
		String[] result = new String[size];
		try {
			for (int i = 0; i < size; i++)
				result[i] = ioBuffer.getString(ioBuffer.getShort(), utf8Decoder);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		return result;
	}
}
